﻿/*********************************************************************************************
** Jquery extend
*********************************************************************************************/
$.HtmlEncode = function (text) {
    var ret = "";
    if (typeof text == "string") {
        ret = text
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
    }
    return ret;
};
$.HtmlDecode = function (text) {
    var ret = text;
    if (typeof text == "string") {
        ret = text
            .replace(/&amp;/g, '&')
            .replace(/&quot;/g, '"')
            .replace(/&#39;/g, '\'')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/\\u0026amp;/g, '&')
            .replace(/\\u0026quot;/g, '"')
            .replace(/\\u0026#39;/g, '\'')
            .replace(/\\u0026lt;/g, '<')
            .replace(/\\u0026gt;/g, '>');
    }
    return ret;
};
$.GetURL = function (key, _default) {
    _default = _default || "";
    var result = _default;
    if (typeof key == "undefined") {
        return result;
    }
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]").toLowerCase();
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var url = location.search;
    if (url) {
        url = url.toLowerCase();
    }
    var queryString = regex.exec(url);
    var arrQueryOrigin = [];
    $.each(location.search.substr(1).split('&'), function (i, q) {
        var item = q.split('=');
        arrQueryOrigin.push(item);
    });
    if (queryString == null) {
        return result;
    }
    else {
        result = queryString[1];
        for (var i in arrQueryOrigin) {
            var name = arrQueryOrigin[i][0];
            var value = arrQueryOrigin[i][1];
            var query = name + "=" + value;
            var qs = queryString[0].toLowerCase().replace(/\&|\?/g, "");
            if (query.toLowerCase() == qs) {
                result = value;
            }
        }
        return result;
    }
};
/*********************************************************************************************
** Get & Set cookies
*********************************************************************************************/
$.SetCookie = function (c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + '; path=/';
};

$.GetCookie = function (c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
};
$.GetExtension = function (fileName) {
    var re = /(?:\.([^.]+))?$/;
    return re.exec(fileName)[1];
};
$.GuidGenerator = function () {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
};
$.RemoveHTMLTags = function (htmlString) {
    if (htmlString) {
        var mydiv = document.createElement("div");
        mydiv.innerHTML = htmlString;

        if (document.all) // IE Stuff
        {
            return mydiv.innerText;

        }
        else // Mozilla does not work with innerText
        {
            return mydiv.textContent;
        }
    }
};
/*********************************************************************************************
* jquery.ajax
*********************************************************************************************/
$.Ajax = function (options) {
    //if (options) {
    //    //if (options.data) {
    //    //    var data = {};
    //    //    $.each(options.data, function (key, value) {
    //    //        data[key] = $.HtmlEncode(value);
    //    //    });
    //    //    options.data = data;
    //    //}
    //    var fn_beforeSend = options.beforeSend;
    //    var fn_complete = options.complete;
    //    var fn_error = options.error;
    //    var fn_success = options.success;
    //    if (typeof fn_success == "function") {
    //        options.success = function (data, textStatus, xhr) {
    //            //if (typeof data == "string")
    //            //    data = $.HtmlDecode(data);
    //            fn_success(data, textStatus, xhr);
    //        };
    //    }
    //}
    return $.ajax(options);
};


/*********************************************************************************************
** Get Attributes 
**    $('#elm').GetAttributes();  // Get all attributes
**    $('#elm').GetAttributes(['id', 'class']);  // Get ll attributes except id and class
*********************************************************************************************/
$.fn.GetAttributes = function (except) {
    var attributes = {};
    if (except) {
        except = $.map(except, function (item) {
            return item.toString().toLowerCase();
        });
    };
    this.each(function () {
        var attrs = $.map(this.attributes, function (item) {
            return item.name.toString().toLowerCase();
        });
        if (except) {
            attrs = $.grep(attrs, function (item, index) {
                return $.inArray(item, except) == -1;
            });
        }
        var handle = $(this);
        $.each(attrs, function (index, item) {
            attributes[item] = handle.attr(item);
        });
    });
    return attributes;
}
/*********************************************************************************************
** Remove Attributes 
**    $('#elm').removeAttributes(['id', 'class']);  // remove id and class attributes
**    $('#elm').removeAttributes(null, ['href']);  // remove all attributes except href
*********************************************************************************************/

$.fn.RemoveAttributes = function (only, except) {
    if (only) {
        only = $.map(only, function (item) {
            return item.toString().toLowerCase();
        });
    };
    if (except) {
        except = $.map(except, function (item) {
            return item.toString().toLowerCase();
        });
        if (only) {
            only = $.grep(only, function (item, index) {
                return $.inArray(item, except) == -1;
            });
        };
    };
    return this.each(function () {
        var attributes;
        if (!only) {
            attributes = $.map(this.attributes, function (item) {
                return item.name.toString().toLowerCase();
            });
            if (except) {
                attributes = $.grep(attributes, function (item, index) {
                    return $.inArray(item, except) == -1;
                });
            };
        } else {
            attributes = only;
        }
        var handle = $(this);
        $.each(attributes, function (index, item) {
            handle.removeAttr(item);
        });
    });
};
/********************************************
var result = $.string.Format("Hello, {0}.", "world");
//result -> "Hello, world."
*********************************************/
$.string = {
    Format: function (text) {
        //check if there are two arguments in the arguments list
        if (arguments.length <= 1) {
            //if there are not 2 or more arguments there's nothing to replace
            //just return the text
            return text;
        }
        //decrement to move to the second argument in the array
        var tokenCount = arguments.length - 2;
        for (var token = 0; token <= tokenCount; ++token) {
            //iterate through the tokens and replace their placeholders from the text in order
            var reg = new RegExp("\\{" + token + "\\}", "gi");
            var value = arguments[token + 1];
            text = text.replace(reg, value);

        }
        return text;
    },
    IsNullOrEmpty: function (text) {
        if (typeof text == "undefined")
            return true;
        var value = $.trim(text);
        if (value.length == 0)
            return true
        return false;
    },
    Compare: function (strA, strB, ignoreCase) {
        if (typeof ignoreCase == "undefined")
            ignoreCase = false;
        if (typeof strA != "undefined" && typeof strB != "undefined" && typeof strA == "string" && typeof strB == "string") {
            if (ignoreCase) {
                strA = strA.toLowerCase();
                strB = strB.toLowerCase();
            }
            return strA === strB;
        }
        return false;
    }
};
$.json2xml = function (o, tab) {
    var toXml = function (v, name, ind) {
        var xml = "";
        if (v instanceof Array) {
            for (var i = 0, n = v.length; i < n; i++)
                xml += ind + toXml(v[i], name, ind + "\t") + "\n";
        }
        else if (typeof (v) == "object") {
            var hasChild = false;
            xml += ind + "<" + name;
            for (var m in v) {
                if (m.charAt(0) == "@")
                    xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
                else
                    hasChild = true;
            }
            xml += hasChild ? ">" : "/>";
            if (hasChild) {
                for (var m in v) {
                    if (m == "#text")
                        xml += v[m];
                    else if (m == "#cdata")
                        xml += "<![CDATA[" + v[m] + "]]>";
                    else if (m.charAt(0) != "@")
                        xml += toXml(v[m], m, ind + "\t");
                }
                xml += (xml.charAt(xml.length - 1) == "\n" ? ind : "") + "</" + name + ">";
            }
        }
        else {
            xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
        }
        return xml;
    }, xml = "";
    for (var m in o)
        xml += toXml(o[m], m, "");
    return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
};
$.xml2json = function (xml, tab) {
    var X = {
        toObj: function (xml) {
            var o = {};
            if (xml.nodeType == 1) {   // element node ..
                if (xml.attributes.length)   // element with attributes  ..
                    for (var i = 0; i < xml.attributes.length; i++)
                        o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
                if (xml.firstChild) { // element has child nodes ..
                    var textChild = 0, cdataChild = 0, hasElementChild = false;
                    for (var n = xml.firstChild; n; n = n.nextSibling) {
                        if (n.nodeType == 1) hasElementChild = true;
                        else if (n.nodeType == 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
                        else if (n.nodeType == 4) cdataChild++; // cdata section node
                    }
                    if (hasElementChild) {
                        if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
                            X.removeWhite(xml);
                            for (var n = xml.firstChild; n; n = n.nextSibling) {
                                if (n.nodeType == 3)  // text node
                                    o["#text"] = X.escape(n.nodeValue);
                                else if (n.nodeType == 4)  // cdata node
                                    o["#cdata"] = X.escape(n.nodeValue);
                                else if (o[n.nodeName]) {  // multiple occurence of element ..
                                    if (o[n.nodeName] instanceof Array)
                                        o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
                                    else
                                        o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
                                }
                                else  // first occurence of element..
                                    o[n.nodeName] = X.toObj(n);
                            }
                        }
                        else { // mixed content
                            if (!xml.attributes.length)
                                o = X.escape(X.innerXml(xml));
                            else
                                o["#text"] = X.escape(X.innerXml(xml));
                        }
                    }
                    else if (textChild) { // pure text
                        if (!xml.attributes.length)
                            o = X.escape(X.innerXml(xml));
                        else
                            o["#text"] = X.escape(X.innerXml(xml));
                    }
                    else if (cdataChild) { // cdata
                        if (cdataChild > 1)
                            o = X.escape(X.innerXml(xml));
                        else
                            for (var n = xml.firstChild; n; n = n.nextSibling)
                                o["#cdata"] = X.escape(n.nodeValue);
                    }
                }
                if (!xml.attributes.length && !xml.firstChild) o = null;
            }
            else if (xml.nodeType == 9) { // document.node
                o = X.toObj(xml.documentElement);
            }
            else
                alert("unhandled node type: " + xml.nodeType);
            return o;
        },
        toJson: function (o, name, ind) {
            var json = name ? ("\"" + name + "\"") : "";
            if (o instanceof Array) {
                for (var i = 0, n = o.length; i < n; i++)
                    o[i] = X.toJson(o[i], "", ind + "\t");
                json += (name ? ":[" : "[") + (o.length > 1 ? ("\n" + ind + "\t" + o.join(",\n" + ind + "\t") + "\n" + ind) : o.join("")) + "]";
            }
            else if (o == null)
                json += (name && ":") + "null";
            else if (typeof (o) == "object") {
                var arr = [];
                for (var m in o)
                    arr[arr.length] = X.toJson(o[m], m, ind + "\t");
                json += (name ? ":{" : "{") + (arr.length > 1 ? ("\n" + ind + "\t" + arr.join(",\n" + ind + "\t") + "\n" + ind) : arr.join("")) + "}";
            }
            else if (typeof (o) == "string")
                json += (name && ":") + "\"" + o.toString() + "\"";
            else
                json += (name && ":") + o.toString();
            return json;
        },
        innerXml: function (node) {
            var s = ""
            if ("innerHTML" in node)
                s = node.innerHTML;
            else {
                var asXml = function (n) {
                    var s = "";
                    if (n.nodeType == 1) {
                        s += "<" + n.nodeName;
                        for (var i = 0; i < n.attributes.length; i++)
                            s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
                        if (n.firstChild) {
                            s += ">";
                            for (var c = n.firstChild; c; c = c.nextSibling)
                                s += asXml(c);
                            s += "</" + n.nodeName + ">";
                        }
                        else
                            s += "/>";
                    }
                    else if (n.nodeType == 3)
                        s += n.nodeValue;
                    else if (n.nodeType == 4)
                        s += "<![CDATA[" + n.nodeValue + "]]>";
                    return s;
                };
                for (var c = node.firstChild; c; c = c.nextSibling)
                    s += asXml(c);
            }
            return s;
        },
        escape: function (txt) {
            return txt.replace(/[\\]/g, "\\\\")
                      .replace(/[\"]/g, '\\"')
                      .replace(/[\n]/g, '\\n')
                      .replace(/[\r]/g, '\\r');
        },
        removeWhite: function (e) {
            e.normalize();
            for (var n = e.firstChild; n;) {
                if (n.nodeType == 3) {  // text node
                    if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
                        var nxt = n.nextSibling;
                        e.removeChild(n);
                        n = nxt;
                    }
                    else
                        n = n.nextSibling;
                }
                else if (n.nodeType == 1) {  // element node
                    X.removeWhite(n);
                    n = n.nextSibling;
                }
                else                      // any other node
                    n = n.nextSibling;
            }
            return e;
        }
    };
    if (xml.nodeType == 9) // document node
        xml = xml.documentElement;
    var json = X.toJson(X.toObj(X.removeWhite(xml)), xml.nodeName, "\t");
    return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
};
$.findInXml = function (xmlData, tagName) {
    tagName = tagName || "string";
    try {
        var ret = xmlData;
        if ($.browser.msie && parseInt($.browser.version, 10) <= 8) {
            ret = xmlData.documentElement.childNodes[0].text;
        }
        else {
            ret = $(xmlData).find(tagName).text();
        }
        return ret;
    } catch (e) {
        return "";
    }

};